package com.vancouver.knows.ui.activity.userpost;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.Html;
import android.text.InputFilter;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextWatcher;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.pangu.service.ActionException;
import com.pangu.task.IResultReceiver;
import com.pangu.task.mark.ATaskMark;
import com.pangu.util.FileUtil;
import com.pangu.util.StringUtil;
import com.stripe.android.model.Token;
import com.vancouver.knows.R;
import com.vancouver.knows.business.bean.PostDetailInfo;
import com.vancouver.knows.business.bean.SubcategoryInfo;
import com.vancouver.knows.business.bean.UserInfo;
import com.vancouver.knows.business.task.mark.FetchUserPostDetailTaskMark;
import com.vancouver.knows.business.task.mark.UploadBusinessPhotosTaskMark;
import com.vancouver.knows.business.task.mark.UploadUserPostTaskMark;
import com.vancouver.knows.ui.activity.login.LoginActivity;
import com.vancouver.knows.ui.activity.my.MyFeedbackAboutProcotolActivity;
import com.vancouver.knows.ui.base.BaseActivity;
import com.vancouver.knows.ui.fragment.citynews.Crop;
import com.vancouver.knows.ui.fragment.citynews.SelectPicWindow;
import com.vancouver.knows.util.AppUtils;
import com.vancouver.knows.util.PhoConstants;

import java.io.File;
import java.text.DecimalFormat;

import butterknife.Bind;
import butterknife.OnClick;


/**
 * Created by Chris Li on 2016-07-18.
 */
public class CreateUserPostActivity extends BaseActivity implements View.OnClickListener, PhotosAdapter.PhotoAdapterListener, IResultReceiver, TextWatcher {

    public static final String CATEGORY_EXTRA = "category_extra";
    public static final String SUBCATEGORY_EXTRA = "subcategory_extra";
    public static final String SUBCATEGORY_PRICE_EXTRA = "subcategory_price_extra";
    public static final String EDIT_MODE_EXTRA = "edit_mode_extra";
    public static final String ADD_PHOTOS_MODE_EXTRA = "add_photo_mode_extra";
    public static final String STATUS_EXTRA = "status_extra";
    public static final String POST_ID_EXTRA = "post_id_extra";

    public static final String DRAFT_STATUS = "draft";
    public static final String PUBLISH_STATUS = "publish";

    public static final int CREATE_POST_SUCCESS_REQUEST = 200;
    public static final int ADD_PHOTOS_REQUEST = 201;

    @Bind(R.id.toolbar_title)
    TextView mToolbarTitle;
    @Bind(R.id.content_title)
    TextView mContentTitle;
    @Bind(R.id.content_input)
    EditText mContentInput;
    @Bind(R.id.category_text)
    TextView mCategoryText;
    @Bind(R.id.location_text)
    TextView mLocationText;
    @Bind(R.id.phone_input)
    EditText mPhoneInput;
    @Bind(R.id.email_input)
    EditText mEmailInput;
    @Bind(R.id.price_input)
    EditText mPriceInput;
    @Bind(R.id.photo_container)
    RecyclerView mPhotoContainer;
    @Bind(R.id.disclaimer_text)
    TextView mDisclaimerText;
    @Bind(R.id.top_right_icon)
    TextView mTopRightIcon;
    @Bind(R.id.save_button)
    Button mSaveButton;
    @Bind(R.id.upload_button)
    Button mUploadButton;
    @Bind(R.id.button_container)
    LinearLayout mButtonContainer;
    @Bind(R.id.loading_view)
    RelativeLayout mLoadingView;
    @Bind(R.id.category_title)
    TextView mCategoryTitle;
    @Bind(R.id.category_picker)
    RelativeLayout mCategoryPicker;
    @Bind(R.id.contact_title)
    TextView mContactTitle;
    @Bind(R.id.location_picker)
    RelativeLayout mLocationPicker;
    @Bind(R.id.phone_input_container)
    RelativeLayout mPhoneInputContainer;
    @Bind(R.id.email_input_container)
    RelativeLayout mEmailInputContainer;
    @Bind(R.id.price_title)
    TextView mPriceTitle;
    @Bind(R.id.price_input_container)
    RelativeLayout mPriceInputContainer;

    private PhotosAdapter mPhotosAdapter;
    private SelectPicWindow mSelectPicDialog;
    private String mLocalFilePath;

    private String mChosenCategorySlug;
    private String mChosenSubcategorySlug;
    private String mCurrentPostId = null;

    private boolean mHasFee = false;
    private float mPrice = 0;
    private boolean mHasBeenEdited = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create_user_post);

        mPhotoContainer.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        mPhotoContainer.setNestedScrollingEnabled(false);
        mPhotosAdapter = new PhotosAdapter(this);
        mPhotosAdapter.setListener(this);
        mPhotoContainer.setAdapter(mPhotosAdapter);

        setDisclaimerText();
        mSelectPicDialog = new SelectPicWindow(this, this);
        mTopRightIcon.setEnabled(false);

        mLoadingView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return true;
            }
        });

        if (imContext.getSharedPrefManager().getUserMeta() != null) {
            // pre-fill user contact data.
            UserInfo.UserMeta userMeta = imContext.getSharedPrefManager().getUserMeta();
            mLocationText.setText(userMeta.getCity());
            mPhoneInput.setText(userMeta.getPhone());
            mEmailInput.setText(userMeta.getEmail());
        }

        Intent intent = getIntent();
        if (intent.getBooleanExtra(EDIT_MODE_EXTRA, false)) {
            mToolbarTitle.setText(R.string.post_update_title);
            populatePostData(intent);
        } else if (intent.getBooleanExtra(ADD_PHOTOS_MODE_EXTRA, false)) {
            setAddPhotosView(intent);
        } else {
            setCategory(intent);
            setTextWatchers();
        }
    }

    private void setAddPhotosView(Intent intent) {

        mCurrentPostId = intent.getStringExtra(POST_ID_EXTRA);
        if (mCurrentPostId == null) {
            finish();
        }

        mToolbarTitle.setText(R.string.add_photos_title);
        mContentTitle.setText(R.string.photo_caption_title);
        mContentInput.setHint(R.string.photo_caption_hint);

        // set max length to 30
        InputFilter[] filterArray = new InputFilter[1];
        filterArray[0] = new InputFilter.LengthFilter(30);
        mContentInput.setFilters(filterArray);
        mContentInput.addTextChangedListener(this);

        mCategoryTitle.setVisibility(View.GONE);
        mCategoryPicker.setVisibility(View.GONE);
        mContactTitle.setVisibility(View.GONE);
        mLocationPicker.setVisibility(View.GONE);
        mPhoneInputContainer.setVisibility(View.GONE);
        mEmailInputContainer.setVisibility(View.GONE);
        mPriceTitle.setVisibility(View.GONE);
        mPriceInputContainer.setVisibility(View.GONE);
        mSaveButton.setVisibility(View.GONE);

        RelativeLayout.LayoutParams buttonContainerParams = (RelativeLayout.LayoutParams) mButtonContainer.getLayoutParams();
        buttonContainerParams.addRule(RelativeLayout.BELOW, 0);

        setDisclaimerText();
    }

    private void setDisclaimerText() {
        if (getIntent().getBooleanExtra(ADD_PHOTOS_MODE_EXTRA, false)) {
            mDisclaimerText.setText(Html.fromHtml(getString(R.string.photo_terms)));
        } else {
            mDisclaimerText.setText(Html.fromHtml(getString(R.string.posting_terms)));
        }

        mDisclaimerText.setMovementMethod(LinkMovementMethod.getInstance());

        final String tosText = getString(R.string.menu_item_tos);
        String disclaimerText = mDisclaimerText.getText().toString();
        int startIndex = disclaimerText.indexOf(tosText);
        int endIndex = startIndex + tosText.length();

        CharSequence text = mDisclaimerText.getText();
        SpannableString spannable = SpannableString.valueOf(text);
        spannable.setSpan(new ClickableSpan() {
            @Override
            public void updateDrawState(TextPaint ds) {
                ds.setColor(ContextCompat.getColor(CreateUserPostActivity.this, R.color.orange));
                ds.setUnderlineText(false);
            }

            @Override
            public void onClick(View widget) {
                Intent intent = new Intent(CreateUserPostActivity.this, MyFeedbackAboutProcotolActivity.class);
                intent.putExtra("USER_NOTICE", tosText);
                intent.putExtra("PAGE_TYPE", "user_terms");
                startActivity(intent);
            }
        }, startIndex, endIndex, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    }

    private void populatePostData(Intent intent) {
        mCurrentPostId = intent.getStringExtra(POST_ID_EXTRA);
        if (mCurrentPostId == null) {
            finish();
            return;
        }

        String status = intent.getStringExtra(STATUS_EXTRA);
        if (status.equals(DRAFT_STATUS)) {
            mSaveButton.setVisibility(View.GONE);
        } else if (status.equals(PUBLISH_STATUS)) {
            mTopRightIcon.setText(R.string.update);
            mButtonContainer.setVisibility(View.GONE);
        }

        mLoadingView.setVisibility(View.VISIBLE);
        String userId = imContext.getSharedPrefManager().getUserId();
        ATaskMark aTaskMark = imContext.getBusinessModule().getTaskMarkPool().getFetchUserPostDetailTaskMark(mCurrentPostId);
        imContext.getBusinessModule().getServiceWrapper().fetchUserPostDetail(this, aTaskMark, mCurrentPostId, userId, imContext.latitude, imContext.longitude);
    }

    private void setCategory(Intent intent) {

        if (intent == null) {
            return;
        }

        mChosenCategorySlug = intent.getStringExtra(CATEGORY_EXTRA);
        SubcategoryInfo chosenSubcategory = (SubcategoryInfo) intent.getSerializableExtra(SUBCATEGORY_EXTRA);
        mChosenSubcategorySlug = chosenSubcategory.getSlug();

        String categoryHeading = "";
        switch (mChosenCategorySlug) {

            case UserPostFilterActivity.BUY_AND_SELL_SLUG:
                categoryHeading = getString(R.string.category_buy_and_sell);
                break;

            case UserPostFilterActivity.FRIENDS_AND_PARTNERS_SLUG:
                categoryHeading = getString(R.string.category_friends_and_partners);
                break;

            case UserPostFilterActivity.HOUSING_SLUG:
                categoryHeading = getString(R.string.category_housing);
                break;

            case UserPostFilterActivity.JOBS_SLUG:
                categoryHeading = getString(R.string.category_jobs);
                break;

            case UserPostFilterActivity.MUTUAL_SUPPORT_SLUG:
                categoryHeading = getString(R.string.category_mutual_support);
                break;
        }

        categoryHeading += " > " + chosenSubcategory.getName();
        mCategoryText.setText(categoryHeading);

        mPrice = intent.getFloatExtra(SUBCATEGORY_PRICE_EXTRA, 0);
        if (mPrice > 0) {
            mHasFee = true;
            mUploadButton.setText(getString(R.string.cost_upload, new DecimalFormat("#.##").format(mPrice)));
        } else {
            mHasFee = false;
        }
    }

    private void setTextWatchers() {
        mContentInput.addTextChangedListener(this);
        mPhoneInput.addTextChangedListener(this);
        mEmailInput.addTextChangedListener(this);
        mPriceInput.addTextChangedListener(this);
    }

    @OnClick(R.id.back_icon)
    public void onBackButtonClicked() {
        onBackPressed();
    }

    @OnClick(R.id.top_right_icon)
    public void onActionButtonClicked() {
        if (getLoginStatus()) {
            if (getIntent().getBooleanExtra(ADD_PHOTOS_MODE_EXTRA, false)) { // attach photo to business mode
                uploadBusinessPhotos();
            } else { // default mode
                uploadUserPost(PUBLISH_STATUS);
            }
        }
    }

    @OnClick(R.id.category_picker)
    public void onCategoryPickerClicked() {
        Intent intent = new Intent(this, UserPostSubcategoryListActivity.class);
        intent.putExtra(UserPostSubcategoryListActivity.CATEGORY_EXTRA, mChosenCategorySlug);
        intent.putExtra(UserPostSubcategoryListActivity.REQUEST_CODE_EXTRA,UserPostSubcategoryListActivity.CHOOSE_NEW_SUBCATEGORY_REQUEST);
        startActivityForResult(intent, UserPostSubcategoryListActivity.CHOOSE_NEW_SUBCATEGORY_REQUEST);
    }

    @OnClick(R.id.location_picker)
    public void onLocationPickerClicked() {
        Intent intent = new Intent(this, UserPostSubcategoryListActivity.class);
        intent.putExtra(UserPostSubcategoryListActivity.IS_CITY_CATEGORY_EXTRA, true);
        intent.putExtra(UserPostSubcategoryListActivity.SELECTED_CITY_DATA, mLocationText.getText().toString());
        startActivityForResult(intent, UserPostSubcategoryListActivity.CHOOSE_CITY_REQUEST);
    }

    @OnClick(R.id.save_button)
    public void onSaveButtonClicked() {
        if (getLoginStatus()) {
            uploadUserPost(DRAFT_STATUS);
        }
    }

    @OnClick(R.id.upload_button)
    public void onUploadButtonClicked() {
        if (getLoginStatus()) {
            if (getIntent().getBooleanExtra(ADD_PHOTOS_MODE_EXTRA, false)) { // attach photo to business mode
                uploadBusinessPhotos();
            } else { // default mode
                uploadUserPost(PUBLISH_STATUS);
            }
        }
    }

    private void uploadBusinessPhotos() {

        String caption = mContentInput.getText().toString().trim();
        String userId = imContext.getSharedPrefManager().getUserId();

        if (mPhotosAdapter.getImages().size() > 0) {
            mLoadingView.setVisibility(View.VISIBLE);
            UploadBusinessPhotosTaskMark uploadBusinessPhotosTaskMark = imContext.getBusinessModule().getTaskMarkPool().getUploadBusinessPhotosTaskMark();
            imContext.getBusinessModule().getServiceWrapper()
                    .uploadBusinessPhotos(this,
                            uploadBusinessPhotosTaskMark,
                            userId,
                            mCurrentPostId,
                            mPhotosAdapter.getImages(),
                            caption);
        }
    }

    private void uploadUserPost(String postStatus) {

        String postContent = mContentInput.getText().toString().trim();
        String location = mLocationText.getText().toString().trim();
        String price = mPriceInput.getText().toString().trim();
        String phone = mPhoneInput.getText().toString().trim();
        String email = mEmailInput.getText().toString().trim();
        String userId = imContext.getSharedPrefManager().getUserId();

        if (postStatus.equals(DRAFT_STATUS)) {
            if (!StringUtil.isEmptyString(postContent)) {
                mLoadingView.setVisibility(View.VISIBLE);
                UploadUserPostTaskMark uploadUserPostTaskMark = imContext.getBusinessModule().getTaskMarkPool().getUploadUserPostTaskMark();
                uploadUserPostTaskMark.setPostStatus(DRAFT_STATUS);
                imContext.getBusinessModule().getServiceWrapper()
                        .uploadUserPost(this,
                                uploadUserPostTaskMark,
                                userId,
                                mCurrentPostId,
                                postContent,
                                mPhotosAdapter.getImages(),
                                DRAFT_STATUS,
                                mChosenCategorySlug,
                                mChosenSubcategorySlug,
                                price,
                                location,
                                phone,
                                email);
            } else {
                Toast.makeText(this, R.string.addpost_no_content, Toast.LENGTH_SHORT).show();
            }
        } else if (postStatus.equals(PUBLISH_STATUS)) {
            if (validatePublishablePost(postContent, location, phone, email)) {
                if (mHasFee) {
                    UserInfo.UserMeta userMeta = imContext.getSharedPrefManager().getUserMeta();
                    String username = imContext.getSharedPrefManager().getUserName();
                    PaymentDialog paymentDialog = new PaymentDialog(this, userMeta, username, mPrice, new PaymentDialog.OnPaymentDialogResultListener() {
                        @Override
                        public void onStripeTokenRetrieved(Token token) {
                            Log.i(TAG, token.getId());
                        }
                    });
                    paymentDialog.show();
                } else {
                    publishUserPost(userId, postContent, price, location, phone, email);
                }
            }
        }
    }

    private void publishUserPost(String userId, String postContent, String price, String location, String phone, String email) {
        mLoadingView.setVisibility(View.VISIBLE);
        UploadUserPostTaskMark uploadUserPostTaskMark = imContext.getBusinessModule().getTaskMarkPool().getUploadUserPostTaskMark();
        uploadUserPostTaskMark.setPostStatus(PUBLISH_STATUS);
        imContext.getBusinessModule().getServiceWrapper()
                .uploadUserPost(this,
                        uploadUserPostTaskMark,
                        userId,
                        mCurrentPostId,
                        postContent,
                        mPhotosAdapter.getImages(),
                        PUBLISH_STATUS,
                        mChosenCategorySlug,
                        mChosenSubcategorySlug,
                        price,
                        location,
                        phone,
                        email);
    }

    private boolean validatePublishablePost(String postContent, String location, String phone, String email) {

        if (StringUtil.isEmptyString(postContent)) {
            Toast.makeText(this, R.string.addpost_no_content, Toast.LENGTH_SHORT).show();
            return false;
        } else {
            if (StringUtil.isChineseText(postContent)) {
                if (postContent.length() < 8) {
                    Toast.makeText(this, R.string.invalid_post_content_length, Toast.LENGTH_SHORT).show();
                    return false;
                }
            } else {
                String[] words = postContent.split(" ");
                if (words.length < 3) {
                    Toast.makeText(this, R.string.invalid_post_content_length, Toast.LENGTH_SHORT).show();
                    return false;
                }
            }
        }

        if (StringUtil.isEmptyString(location)) {
            Toast.makeText(this, R.string.empty_location, Toast.LENGTH_SHORT).show();
            return false;
        }

        if (StringUtil.isEmptyString(phone) && StringUtil.isEmptyString(email)) {
            Toast.makeText(this, R.string.invalid_phone_or_email, Toast.LENGTH_SHORT).show();
            return false;
        } else {

            if (!StringUtil.isEmptyString(phone)) {
                if (!StringUtil.isValidPhoneNumber(phone)) {
                    Toast.makeText(this, R.string.invalid_phone_number, Toast.LENGTH_SHORT).show();
                    return false;
                }
            }

            if (!StringUtil.isEmptyString(email)) {
                if (!StringUtil.isValidEmail(email)) {
                    Toast.makeText(this, R.string.invalid_email, Toast.LENGTH_SHORT).show();
                    return false;
                }
            }
        }

        return true;
    }

    private boolean getLoginStatus() {
        if (imContext.getSharedPrefManager().getUserId() != null) {
            return true;
        } else {
            startActivity(new Intent(this, LoginActivity.class));
            return false;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent result) {

        if (requestCode == UserPostSubcategoryListActivity.CHOOSE_NEW_SUBCATEGORY_REQUEST && resultCode == Activity.RESULT_OK) {
            setCategory(result);
            setHasEdited();
        } else if (requestCode == Crop.REQUEST_PICK && resultCode == Activity.RESULT_OK) {
            Uri uri = result.getData();
            String path = AppUtils.createFile(this, uri, FileUtil.getSdcardStoreDir() + File.separator
                    + PhoConstants.ADD_POST_IMAGE_DIR + System.currentTimeMillis() + ".jpg");
            if (!StringUtil.isEmptyString(path)) {
                mPhotosAdapter.addImage(path);
                setHasEdited();
            }

        } else if (requestCode == Crop.REQUEST_CAMERA && resultCode == Activity.RESULT_OK) {
            mPhotosAdapter.addImage(mLocalFilePath);
            setHasEdited();
        } else if (requestCode == UserPostSubcategoryListActivity.CHOOSE_CITY_REQUEST && resultCode == Activity.RESULT_OK) {
            String selectedCity = result.getStringExtra(UserPostSubcategoryListActivity.SELECTED_CITY_DATA);
            mLocationText.setText(selectedCity);
            setHasEdited();
        }
    }

    @Override
    protected void onDestroy() {
        mPhotosAdapter.clear();
        String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            String imgDir = FileUtil.getSdcardStoreDir() + File.separator + PhoConstants.ADD_POST_IMAGE_DIR;
            FileUtil.delAllChildrenFiles(imgDir);
        }

        super.onDestroy();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_take_photo:
                mSelectPicDialog.dismiss();
                String state = Environment.getExternalStorageState();
                if (state.equals(Environment.MEDIA_MOUNTED)) {
                    String imgDir = FileUtil.getSdcardStoreDir() + File.separator + PhoConstants.ADD_POST_IMAGE_DIR;
                    File dir = new File(imgDir);
                    if (!dir.exists()) {
                        dir.mkdirs();
                    }

                    mLocalFilePath = imgDir + System.currentTimeMillis() + ".jpg";
                    Crop.cameraImage(this, Crop.REQUEST_CAMERA, Uri.fromFile(new File(mLocalFilePath)));

                } else {
                    Toast.makeText(getApplicationContext(), R.string.check_sdcard, Toast.LENGTH_SHORT).show();
                }

                break;

            case R.id.btn_pick_photo:
                String imgDir = FileUtil.getSdcardStoreDir() + File.separator + PhoConstants.ADD_POST_IMAGE_DIR;
                File dir = new File(imgDir);
                if (!dir.exists()) {
                    dir.mkdirs();
                }
                mSelectPicDialog.dismiss();
                Crop.pickImage(this, Crop.REQUEST_PICK);

                break;
        }
    }

    @Override
    public void onAddImageClicked() {
        if (mPhotosAdapter.getImages().size() < 9) {
            mSelectPicDialog.show();
        } else {
            Toast.makeText(getApplicationContext(), R.string.max_photos, Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onImageClicked(String imagePath) {

    }

    @Override
    public void receiveResult(ATaskMark taskMark, ActionException exception, Object trackerResult) {

        mLoadingView.setVisibility(View.GONE);
        if (exception != null) {
            Toast.makeText(this, exception.getExMessage(), Toast.LENGTH_SHORT).show();
            Log.e(TAG, exception.getExMessage());
        } else {
            if (taskMark instanceof UploadUserPostTaskMark) {
                UploadUserPostTaskMark uploadUserPostTaskMark = (UploadUserPostTaskMark) taskMark;
                if (uploadUserPostTaskMark.getPostStatus().equals(DRAFT_STATUS)) {
                    mCurrentPostId = imContext.getBusinessModule().getCacheManager().getUploadedUserPostDetailInfo().getPostId();
                    mSaveButton.setText(R.string.saved_text);
                    mSaveButton.setBackgroundColor(ContextCompat.getColor(this, R.color.dark_button_color));
                    mSaveButton.setTextColor(ContextCompat.getColor(this, R.color.orange));
                    mSaveButton.setEnabled(false);
                    getIntent().putExtra(EDIT_MODE_EXTRA, true);
                    getIntent().putExtra(STATUS_EXTRA, DRAFT_STATUS);
                    mPhotosAdapter.setNewImageStartIndex();
                } else if (uploadUserPostTaskMark.getPostStatus().equals(PUBLISH_STATUS)) {
                    mCurrentPostId = imContext.getBusinessModule().getCacheManager().getUploadedUserPostDetailInfo().getPostId();
                    mTopRightIcon.setText(R.string.update);
                    mTopRightIcon.setTextColor(ContextCompat.getColor(this, R.color.common_light_gray));
                    mButtonContainer.setVisibility(View.GONE);
                    showSuccessDialog();
                }

                mHasBeenEdited = false;
            } else if (taskMark instanceof FetchUserPostDetailTaskMark) {
                PostDetailInfo postDetailInfo = imContext.getBusinessModule().getCacheManager().getUserPostDetailInfoCache().get(mCurrentPostId).getPostDetails();
                if (postDetailInfo != null) {
                    mContentInput.setText(postDetailInfo.getContent());
                    mLocationText.setText(postDetailInfo.getCity());
                    String categoryText = "";
                    if (postDetailInfo.getCategory() != null && postDetailInfo.getCategory().size() > 0) {
                        mChosenCategorySlug = postDetailInfo.getCategory().get(0).getSlug();
                        categoryText = postDetailInfo.getCategory().get(0).getName();
                    }

                    if (postDetailInfo.getSubcategory() != null && postDetailInfo.getSubcategory().size() > 0) {
                        SubcategoryInfo subcategoryInfo = postDetailInfo.getSubcategory().get(0);
                        mChosenSubcategorySlug = subcategoryInfo.getSlug();
                        categoryText += " > " + subcategoryInfo.getName();

                        if (subcategoryInfo.getPrice() > 0) {
                            mHasFee = true;
                            mPrice = subcategoryInfo.getPrice();
                            mUploadButton.setText(getString(R.string.cost_upload, new DecimalFormat("#.##").format(mPrice)));
                        }
                    }

                    if (!StringUtil.isEmptyString(categoryText)) {
                        mCategoryText.setText(categoryText);
                    }

                    mPriceInput.setText(postDetailInfo.getPrice());
                    if (postDetailInfo.getAttachedImages().size() > 0) {
                        mPhotosAdapter.setImages(postDetailInfo.getAttachedImages());
                    }
                }

                mHasBeenEdited = false;
                setTextWatchers();
            } else if (taskMark instanceof UploadBusinessPhotosTaskMark) {
                Toast.makeText(this, R.string.photo_upload_success, Toast.LENGTH_SHORT).show();
                setResult(RESULT_OK);
                finish();
            }
        }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        /* no-op */
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        /* no-op */
    }

    @Override
    public void afterTextChanged(Editable s) {
        if (s.toString().length() > 0) {
            setHasEdited();
        }
    }

    private void setHasEdited() {
        mHasBeenEdited = true;
        mTopRightIcon.setTextColor(ContextCompat.getColor(this, R.color.orange));
        mTopRightIcon.setEnabled(true);
    }

    @Override
    public void onBackPressed() {
        if (mHasBeenEdited) {
            if (mCurrentPostId == null) {
                showSaveDialog();
            } else {
                String status = getIntent().getStringExtra(STATUS_EXTRA);
                if (!StringUtil.isEmptyString(status)) {
                    if (status.equals(DRAFT_STATUS)) {
                        showSaveDialog();
                    } else { // PUBLISH_STATUS
                        showQuitDialog();
                    }
                } else {
                    showQuitDialog();
                }
            }
        } else {
            super.onBackPressed();
        }
    }

    private void showSaveDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.AlertDialogTheme);
        builder.setTitle(R.string.alert_save_title);
        builder.setPositiveButton(R.string.alert_save_and_update, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                uploadUserPost(DRAFT_STATUS);
            }
        });
        builder.setNegativeButton(R.string.alert_exit_no_save, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                finish();
            }
        });

        AlertDialog dialog = builder.create();
        dialog.show();
    }

    private void showQuitDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.AlertDialogTheme);
        builder.setTitle(R.string.alert_quit_title);
        builder.setPositiveButton(R.string.quit, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                finish();
            }
        });
        builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });

        AlertDialog dialog = builder.create();
        dialog.show();
    }

    private void showSuccessDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.AlertDialogTheme);
        builder.setTitle(R.string.alert_post_success_title);
        builder.setMessage(getString(R.string.alert_post_success_message, mCurrentPostId));
        builder.setPositiveButton(R.string.alert_ok, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                setResult(RESULT_OK);
                finish();
            }
        });
        builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                finish();
            }
        });

        AlertDialog dialog = builder.create();
        dialog.show();
    }
}
